package com.lanmao.emc.strategy.impl;

import com.lanmao.emc.enums.UpgradeType;
import com.lanmao.emc.utils.EsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 描述：类似垃圾回收器的升级策略，一次迁移，性能好
 *
 * @author lanmao
 * @since 2024年11月12日 20:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OneMigrationStrategyImpl extends UpgradeStrategyImpl {
    @Override
    public UpgradeType getUpgradeType() {
        return UpgradeType.ONE_MIGRATION;
    }

    @Override
    int upgradeIndex(String indexName, String json, String newIndexName) {
        try {
            //已经是带后缀索引了，恢复正常索引名
            if (EsUtils.existsIndex(newIndexName)) {
                EsUtils.removeAlias(newIndexName, indexName);
                upgrade(json, newIndexName, indexName);
            } else if (EsUtils.existsIndex(indexName)) {
                //已经是正常索引名，使用后缀索引
                upgrade(json, indexName, newIndexName);
                EsUtils.createAlias(newIndexName, indexName);
                log.info("add index {} alias success", indexName);
            } else {
                EsUtils.addIndex(indexName, json);
                log.info("create index {} success", indexName);
            }
        } catch (Exception e) {
            return handleException(indexName, indexName, newIndexName, e);
        }
        return 1;
    }

    private void upgrade(String json, String currIndex, String newIndex) throws Exception {
        EsUtils.addIndex(newIndex, json);
        log.info("create index {} success", newIndex);

        long count = EsUtils.reindexAndGetCount(currIndex, newIndex);
        log.info("reindex index {} success,count {}", newIndex, count);

        EsUtils.delIndex(currIndex);
        log.info("delete index {} success", currIndex);

    }
}